Vue.component('carts', {
  props: ['product'],

  data() {
    return {
      items: []
    }
  },

  watch: {
    product(value) {
      let p = this.items.find((item) => {
        return item.id === value.id
      })
      if (!p) {
        let { id, name, price } = value
        this.items.push({
          id,
          name,
          price,
          quantity: 1
        })
      } else {
        p.quantity++
      }
    }
  },

  computed: {
    total() {
      return this.items.reduce((sum, item) => {
        sum += item.price * item.quantity
        return sum
      }, 0)
    }
  },

  template: `
    <div>
      <ul>
        <li v-for="item in items">
          {{item.name}}: ￥{{item.price}} x {{item.quantity}} = ￥{{item.price * item.quantity}}元
        </li>
      </ul>
      <div v-if="total > 0">总价：{{total}}</div>
    </div>
  `
})